package com.sline.day02._03_batch;

import com.sline.util.JdbcUtil;
import org.junit.Test;

import java.sql.Connection;
import java.sql.PreparedStatement;

public class batchTest {
    @Test
    public void noBatchTest() throws Exception {
        String sql = "insert into t_student(name, age) values(?, ?);";

        Connection connection = JdbcUtil.getConnection();

        PreparedStatement preparedStatement = connection.prepareStatement(sql);
        preparedStatement.setString(1, "张三");

        long begin = System.currentTimeMillis();
        for (int i = 0; i < 5000; i++) {
            preparedStatement.setInt(2, i);
            preparedStatement.executeUpdate();
        }
        long end = System.currentTimeMillis();
        System.out.println("共花了：" + (end - begin) + "ms");
    }
    @Test
    public void batchTest() throws Exception {
        String sql = "insert into t_student(name, age) values('张三', ?)";

        Connection connection = JdbcUtil.getConnection();

        PreparedStatement preparedStatement = connection.prepareStatement(sql);

        long begin = System.currentTimeMillis();
        for (int i = 1; i <= 5000; i++) {
            preparedStatement.setInt(1, i);
            preparedStatement.addBatch();
            if (i % 200 == 0) {
                preparedStatement.executeBatch();
                preparedStatement.clearBatch();
                preparedStatement.clearParameters();
            }
        }
        long end = System.currentTimeMillis();
        System.out.println("共花了：" + (end - begin) + "ms");
    }
}
